<template>
  <el-card>
    <h2>商品管理</h2>
    <!-- 搜索表单 -->
    <el-form :inline="true" class="mb-4">
      <el-form-item label="商品名称">
        <el-input v-model="queryParam.productName" placeholder="请输入商品名称" clearable />
      </el-form-item>

      <el-form-item label="分类">
        <el-select
            v-model="queryParam.categoryId"
            placeholder="请选择分类"
            clearable
            style="width: 120px"
            :loading="categoryLoading"
        >
          <el-option v-for="c in categoryList" :label="c.name" :value="c.id"/>
        </el-select>
      </el-form-item>

      <el-form-item label="品牌">
        <el-select
            v-model="queryParam.brandId"
            placeholder="请选择品牌"
            clearable
            style="width: 120px"
            :loading="loadingBrand"
        >
          <el-option v-for="b in brandList" :label="b.name" :value="b.id"/>
        </el-select>
      </el-form-item>



      <el-form-item label="状态">
        <el-select v-model="queryParam.status" placeholder="请选择状态" clearable style="width: 130px;">
          <el-option label="上架" :value="1" />
          <el-option label="下架" :value="0" />
          <el-option label="售罄" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="loadProducts">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div class="mb-4">
      <el-button type="success" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        添加商品
      </el-button>
    </div>
    <!-- 商品列表 -->
    <el-table :data="products" v-loading="loading" border>
      <el-table-column prop="productId" label="ID" width="80" />
      <el-table-column label="商品图片" width="120">
        <template #default="scope">
          <el-image
              style="width: 80px; height: 80px"
              :src="scope.row.avatar"
              :preview-src-list="[scope.row.avatar]"
              fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column prop="productName" label="商品名称" min-width="180" />
      <el-table-column prop="categoryId" label="分类ID" width="100" />
      <el-table-column prop="brandId" label="品牌ID" width="100" />
      <el-table-column prop="price" label="价格" width="120">
        <template #default="scope">
          ¥{{ scope.row.price.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="stock" label="库存" width="100" />
      <el-table-column prop="status" label="状态" width="120">
        <template #default="scope">
          <el-tag :type="statusTagType(scope.row.status)">
            {{ statusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="280" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.productId)">删除</el-button>
          <el-button
              size="small"
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              @click="handleToggleStatus(scope.row.productId, scope.row.status)"
              :loading="statusLoading[scope.row.productId]"
          >
            {{ scope.row.status === 1 ? '下架' : '上架' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="mt-4 flex justify-end">
      <el-pagination
          v-model:current-page="queryParam.current"
          v-model:page-size="queryParam.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadProducts"
          @current-change="loadProducts"
      />
    </div>

    <!-- 添加/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
      <el-form :model="form" label-width="100px" :rules="rules" ref="formRef">
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入商品名称" />
        </el-form-item>

        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择分类" clearable>
            <el-option
                v-for="item in categoryList"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="品牌" prop="brandId">
          <el-select v-model="form.brandId" placeholder="请选择品牌" clearable>
            <el-option
                v-for="item in brandList"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="价格" prop="price">
          <el-input-number
              v-model="form.price"
              :min="0"
              :precision="2"
              placeholder="请输入价格"
          />
        </el-form-item>

        <el-form-item label="库存" prop="stock">
          <el-input-number
              v-model="form.stock"
              :min="0"
              placeholder="请输入库存"
          />
        </el-form-item>

        <el-form-item label="商品图片" prop="avatar">
          <el-upload
              class="avatar-uploader"
              action="#"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="handleImageChange"
          >
            <img v-if="form.avatar" :src="form.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="商品描述" prop="description">
          <el-input
              v-model="form.description"
              type="textarea"
              :rows="3"
              placeholder="请输入商品描述"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">审核中</el-radio>
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="2">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
  </el-card>
</template>


<script setup>
import { ref, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import axios from 'axios'
import {ElMessage, ElMessageBox} from "element-plus";


// 查询参数
const queryParam = ref({
  current: 1,
  size: 10,
  productName: '',
  categoryId: null,
  brandId: null,
  status: null
})

// 商品列表数据
const products = ref([])
const total = ref(0)
const loading = ref(false)
const submitting = ref(false)
const formRef = ref(null)

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
// 表单数据
const form = ref({
  productId: null,
  productName: '',
  categoryId: null,
  brandId: null,
  price: 0,
  stock: 0,
  status: 1,
  avatar: '',
  description: '',
  deleted: 0
})

// 新增：图片文件临时存储
const imageFile = ref(null)

// 表单验证规则
const rules = {
  productName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  brandId: [
    { required: true, message: '请选择品牌', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格不能小于0', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入库存', trigger: 'blur' },
    { type: 'number', min: 0, message: '库存不能小于0', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 图片上传处理
const handleImageChange = (file) => {
  imageFile.value = file.raw
  form.value.avatar = URL.createObjectURL(file.raw)
}

// 打开添加弹窗
const handleAdd = () => {
  dialogTitle.value = '添加商品'
  Object.assign(form, {
    productId: null,
    productName: '',
    categoryId: null,
    brandId: null,
    price: 0,
    stock: 0,
    status: 1,
    avatar: '',
    description: '',
    deleted: 0
  })
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()
    submitting.value = true

    const formData = new FormData()
    // 只传递后端需要的字段
    const productData = {
      productId: form.value.productId,
      productName: form.value.productName,
      categoryId: form.value.categoryId,
      brandId: form.value.brandId,
      price: form.value.price,
      stock: form.value.stock,
      status: form.value.status,
      description: form.value.description,
      deleted: form.value.deleted,
      avatar: form.value.avatar // 保证编辑时原图片可保留
    }
    formData.append('product', new Blob([JSON.stringify(productData)], {
      type: 'application/json'
    }))
    // 编辑时图片可选
    if (imageFile.value) {
      formData.append('file', imageFile.value)
    }

    const url = form.value.productId
        ? '/api/product/products/updateProduct'
        : '/api/product/products/addProduct'

    const res = await axios.post(url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    if (res.data.code === 200) {
      ElMessage.success(res.data.message)
      dialogVisible.value = false
      loadProducts() // 刷新列表
    } else {
      ElMessage.error(res.data.message || '操作失败')
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.message || error.message || '操作失败')
  } finally {
    submitting.value = false
  }
}


// 加载商品列表
const loadProducts = async () => {
  try {
    loading.value = true
    const res = await axios.post('/api/product/products/findProductList', queryParam.value)
    products.value = res.data.data.records
    total.value = res.data.data.total
  } catch (error) {
    ElMessage.error('获取商品列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 重置查询
const resetQuery = () => {
  queryParam.value = {
    current: 1,
    size: 10,
    productName: '',
    categoryId: null,
    brandId: null,
    status: null
  }
  loadProducts()
}

// 分类下拉列表
const categoryList = ref([])
const loadingCategory = ref(false)

// 获取分类列表
const findCategory = async () => {
  try {
    loadingCategory.value = true
    const res = await axios.get('/api/product/products/findCategorys')
    categoryList.value = res.data.data
  } catch (error) {
    ElMessage.error('获取分类列表失败')
    console.error(error)
  } finally {
    loadingCategory.value = false
  }
}

// 品牌下拉列表
const brandList = ref([])
const loadingBrand = ref(false)

// 获取分类列表
const findBrand = async () => {
  try {
    loadingBrand.value = true
    const res = await axios.get('/api/product/products/findBrands')
    brandList.value = res.data.data
  } catch (error) {
    ElMessage.error('获取分类列表失败')
    console.error(error)
  } finally {
    loadingBrand.value = false
  }
}

// 状态显示转换
const statusText = (status) => {
  switch(status) {
    case 0: return '下架'
    case 1: return '上架'
    case 2: return '售罄'
    default: return '未知'
  }
}

const statusTagType = (status) => {
  switch(status) {
    case 0: return 'info'
    case 1: return 'success'
    case 2: return 'danger'
    default: return ''
  }
}


// 编辑商品
const handleEdit = (row) => {
  dialogTitle.value = '编辑商品'
  Object.assign(form.value, row)
  imageFile.value = null // 清空上次选择的图片
  dialogVisible.value = true
}

// 删除商品
const handleDelete = (productId) => {
  // 先找到商品名称用于提示
  const product = products.value.find(p => p.productId === productId);
  const productName = product ? product.productName : '该商品';

  ElMessageBox.confirm(`确定要删除商品 "${productName}" 吗?`, '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    try {
      // 调用逻辑删除接口
      const res = await axios.post('/api/product/products/luojiDel', { productId });

      if (res.data.code === 200) {
        ElMessage.success('删除成功');
        loadProducts(); // 刷新列表
      } else {
        ElMessage.error(res.data.message || '删除失败');
      }
    } catch (error) {
      ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message));
      console.error('删除失败:', error);
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
}

// 上下架商品
// 加载状态
const statusLoading = ref({})

// 上下架商品
const handleToggleStatus = async (productId, currentStatus) => {
  try {
    statusLoading.value[productId] = true // 设置加载状态

    const newStatus = currentStatus === 1 ? 0 : 1

    // 使用URL query参数方式调用
    const res = await axios.put(`/api/product/products/xiajia?productId=${productId}&status=${newStatus}`)

    if (res.data.code === 200) {
      ElMessage.success(res.data.message || '操作成功')
      loadProducts() // 刷新列表
    } else {
      ElMessage.error(res.data.message || '操作失败')
    }
  } catch (error) {
    ElMessage.error(`操作失败: ${error.response?.data?.message || error.message}`)
    console.error('上下架操作失败:', error)
  } finally {
    statusLoading.value[productId] = false // 清除加载状态
  }
}



// 初始化加载数据
onMounted(() => {
  findCategory()
  findBrand()
  loadProducts()
})
</script>

<style scoped>
.mb-4 {
  margin-bottom: 1rem;
}

/*添加*/
.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 148px;
  height: 148px;
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  text-align: center;
  line-height: 148px;
}

.avatar {
  width: 148px;
  height: 148px;
  display: block;
  object-fit: cover;
}
</style>